package jucTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockResource {
    private int i = 0;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    Condition condition4 = lock.newCondition();

    public void increment() throws InterruptedException {

        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "==>" + "进入判断");
            while (i != 0) {
                System.out.println(Thread.currentThread().getName() + "==>" + "进入开始等待");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "==>" + "等待结束");
            }
            i++;
            System.out.println(Thread.currentThread().getName() + "==>" + i);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "==>" + "进入判断");
            while (i == 0) {
                System.out.println(Thread.currentThread().getName() + "==>" + "进入开始等待");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "==>" + "等待结束");
            }
            i--;
            System.out.println(Thread.currentThread().getName() + "==>" + i);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
